import { Component, OnInit } from '@angular/core';
import { GridConfigService } from '@core/config/grid-config.service';
import { ExportExcelService } from '@core/services/excel/export-excel.service';
import { ApiService } from '@core/services/http/api.service';
import { GridOptions } from '@ag-grid-community/core';
import {ApesMessageService} from "@shared/apes/message";
import {PurchaseService} from "../purchase.service";
import {UserAuthService} from "@core/services/user-auth.service";
import { AllModules, Module } from '@ag-grid-enterprise/all-modules';

@Component({
  selector: 'quotation-monitor',
  templateUrl: './quotation-monitor.component.html',
  styleUrls: ['../purchase-report-form.scss']
})
export class QuotationMonitorComponent implements OnInit {
  /* 按钮相关 */
  buttonBar = [
    { hide: true, style: 'default', label: '导出', id: 'action_export' },
    { hide: true, style: 'default', label: '查询', id: 'action_query',loading: false },
    { hide: true, style: 'default', label: '重置', id: 'action_reset' },
    // { hide: true, style: 'default', label: '展开查询条件', id: 'action_show' },
  ];
  title = '';
  ctx = { model: {} };

  /** Grid 相关 **/
  rowData: any;
  resultData: any;
  gridOptions: GridOptions;
  pinnedBottomRowData: any[] = [];
  columnDefs: any[] = [];
  rowClassRules :any;
  height: any = window.innerHeight - 285 + 'px';
  public modules: Module[] = AllModules;

  // 报错样式
  hind: string = 'none';
  // show: string = 'none';           // 展开查询条件

  // 获取门店、询价区域、销售组
  store:any;
  inquiry:any;
  sale:any;

  mdjcTime: any = [];       // 日期
  startValue: Date = null;
  endValue: Date = null;
  storeID: string;                    // 门店
  inquiryID: any;                     // 询价区域
  saleID: any[];                      // 销售组
  carNum: string;                     // 车牌号
  checkOne: boolean = true;          // 未报价
  checkTwo: boolean = false;         // 已超时

  userInfo = this.userAuthService.getUserInfoObj();
  companyId = this.userInfo.userAccount.post.company.id;
  permitId = this.userInfo.userAccount.post.localPermit.id;
  companyData:any;
  companyList: any[] = [];
  companyClone: any[] = [];

  constructor(private apiService: ApiService,
              private gridConfigService: GridConfigService,
              private exportExcelService: ExportExcelService,
              private msg: ApesMessageService,
              private pa: PurchaseService,
              private userAuthService: UserAuthService,) {
      this.gridInit();
  }

  ngOnInit() {
    this.initialization();
  }

  // gird初始化
  gridInit() {
    this.columnDefs = [
      { 'headerName': '车牌', field: 'CPHM', width: 110, pinned: 'left' },
      { 'headerName': '商品询价单号', field: 'XJDH', width: 120 },
      { 'headerName': '门店', field: 'MDMC', width: 150 },
      { 'headerName': '询价区域', field: 'XJQY' },
      { 'headerName': '报价员', field: 'RYMC' },
      { 'headerName': '销售组', field: 'XSZMC' },
      { 'headerName': '询价时间', field: 'XJRQ_SJ' },
      { 'headerName': '定义耗时', field: 'DYHS',cellRenderer: this.pa.toHour },
      { 'headerName': '供应商耗时', field: 'GYSHS',cellRenderer:this.pa.toHour },
      { 'headerName': '完成询价时间', field: 'WCXJRQ_SJ' },
      { 'headerName': '耗时', field: 'HS',cellRenderer:this.pa.toHour },
      { 'headerName': '超时', field: 'TIO',cellRenderer:this.pa.toHour },
      { 'headerName': '来源单据', field: 'LYDJMC' },
      { 'headerName': '来源单据号码', field: 'LYDJHM' }
    ];

    // 初始化 grid
    this.gridOptions = <GridOptions>{
      toolPanelSuppressSideButtons: true,
      suppressExcelExport: true,
      suppressCsvExport: true,
      suppressSizeToFit: true,
      showToolPanel: false,
      pagination: true,
      paginationPageSize: 100,
      rowHeight: 35,
    };
    this.gridOptions.localeText = this.gridConfigService.getLocaleText();
    this.rowClassRules = {
      // 预警
      'grid-tab-breach': function(params) {
        let now = params.data.TIO;
        return now < 0;
      },
      // 超时
      'grid-tab-warning': function(params) {
        let now = params.data.TIO;
        return now >= 0;
      },
    };

  }

  // 初始化
  initialization() {
    this.pa.getCompany(this.permitId).then(value => {
      this.companyData = value;
      this.companyClone = this.companyData.map( item => {
        return item.id;
      });
      this.queryData();
    });
    this.pa.getSaleData().then(value => { this.sale = value });
    this.pa.getInquiryData().then(value => { this.inquiry = value });
  }

  onEvent(data: any) {
    if (data instanceof MouseEvent) return;
    if (data) {
      if (data.id === 'action_query') {
        this.buttonBar[1].loading = true;
        this.queryData();
      } else if (data.id === 'action_reset') {
        this.action_reset();
      } else if (data.id === 'action_export') {
        this.action_export();
      }
      // else if (data.id === 'action_show') {
      //   this.action_show();
      // }
    }
  }

  // 导出数据
  action_export() {
    if (this.rowData && this.rowData.length === 0) {
      return;
    }
    for(let i = 0 , len=this.rowData.length; i< len ; i++){
      this.rowData[i]['HS'] = this.pa.toHour(this.rowData[i]['HS']);
      this.rowData[i]['TIO'] = this.pa.toHour(this.rowData[i]['TIO']);
    }
    const columnList = this.gridOptions.columnDefs;
    this.exportExcelService.exportWithDealData(columnList, this.rowData, '报价监控');
  }

  // 重置
  action_reset(): void {
    this.mdjcTime = '';
    this.storeID = '';
    this.inquiryID = '';
    this.saleID = [];
    this.carNum = '';
    this.checkOne = true;
    this.checkTwo = false;
    this.companyList = [];
  }

  // 展开查询条件
  // action_show() {
  //   if (this.show === 'none') {
  //     this.show = 'flex';
  //   } else if (this.show === 'flex') {
  //     this.show = 'none';
  //   }
  // }

  // 查询按钮事件
  queryData() {
    this.rowData = [];
    this.pa.getDate(this.mdjcTime, 'startValue', 'endValue', this);
    // 判断日期
    if(this.checkOne === false){
      if (this.pa.getTimeChang(this.endValue, this.startValue, 31) === 'show') {
        this.hind = 'block';
      } else {
        // 判断日期不能为空
        if (this.startValue === null) {
          this.hind = 'block';
        }else{
          this.hind = 'none';
        }
      }
    }else {
      this.hind = 'none';
    }
    //  必须满足以下条件才能调用接口
    if( this.hind === 'none'){
      let list = [];
      if(this.companyList.length <= 0){
        list = this.companyClone;
      }else {
        list = this.companyList;
      }
      const data = { 'interfaceMethod': 'ipmPurchareControlReportService.queryToBeQuoted',
        'pdata': {
          'MDID': this.storeID,
          'XJQY': this.inquiryID,
          'TYBJ': this.checkOne,
          'YCSBJ': this.checkTwo,
          'CPHM': this.carNum,
          'XSZID': this.saleID,
          'START_TYRQ_SJ': this.startValue,
          'END_TYRQ_SJ': this.endValue,
          'companyId': list
        },
      };
      this.pa.getTablesData(data).then(value => {this.rowData = value});
      this.pa.getStoreData(this.companyList).then(value => { this.store = value });
    }
    this.buttonBar[1].loading = false;
  }

}
